<script setup lang="ts">
import { ref } from 'vue'
import { useMemberStore, useDeviceStore } from '@/stores'
import { bindDeviceApi } from '@/services/my'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { dataTransforma,BleWrite } from '@/utils/utils'
const memberStore = useMemberStore()
const deviceStore = useDeviceStore()
//蓝牙连接
const btdevicelist = ref<{ name: string }[]>([])
const deviceId = ref('')
const direct = ref()
const connectBLEsucess = ref(false)
const props = defineProps<{
  type: string
}>()
const isCreateBLEConnection = ref(false)
const show = ref(true)

const closepopup = () => {
  show.value = false
}
onLoad(() => {
  openBluetoothAdapter()
})

//初始化蓝牙模块
const openBluetoothAdapter = () => {
  //console.log('初始化蓝牙模块')

  uni.openBluetoothAdapter({
    success: (success) => {
      //console.log(success + '蓝牙初始化成功')
      uni.showLoading({
        title: '搜索中',
      })
      startBluetoothDevicesDiscovery()
    },
    fail: (err) => {
      uni.showToast({
        title: '蓝牙功能开启失败，请打开蓝牙重试！',
        icon: 'none',
        duration: 1000,
      })
      uni.onBluetoothAdapterStateChange((res) => {
        if (res.available) {
          startBluetoothDevicesDiscovery()
        }
      })
    },
  })
}
//蓝牙搜索附近设备
const startBluetoothDevicesDiscovery = () => {
  uni.startBluetoothDevicesDiscovery({
    allowDuplicatesKey: false,
    success: (res) => {
      console.log(res + '蓝牙开始搜索')
      onBluetoothDeviceFound()
      console.log(btdevicelist.value)
    },
    fail: (err) => {
      console.log(err + '蓝牙搜索失败')
    },
  })
}
//监听获取新蓝牙设备事件
const onBluetoothDeviceFound = () => {
  uni.onBluetoothDeviceFound((res) => {
    //console.log(res , '监听获取新蓝牙设备事件')
    res.devices.forEach((item) => {
      //设备名称是大写SC开头的，使用正则表达式匹配
      if (/^SC/.test(item.name)) {
        //closepopup()
        uni.hideLoading()
        deviceId.value = item.deviceId
        btdevicelist.value.push({ name: item.name })
      }
    })
  })
}

//蓝牙设备连接
const createBLEConnection = (deviceId: string) => {
  console.log('蓝牙设备连接')
  uni.createBLEConnection({
    deviceId,
    success: (res) => {
      console.log('蓝牙设备连接成功', res)
      isCreateBLEConnection.value = true
      getBLEDeviceServices(deviceId)
    },
    fail: (err) => {
      console.log(err + '蓝牙设备连接失败')
      uni.showToast({
        title: '蓝牙设备连接失败,请重试',
        icon: 'none',
      })
    },
  })
}
//获取蓝牙的所有服务
const getBLEDeviceServices = (deviceId: string) => {
  console.log('获取蓝牙的所有服务')
  uni.getBLEDeviceServices({
    deviceId,
    success: (res) => {
      console.log(res)
      res.services.forEach((item) => {
        //蓝牙服务值   0003CDD0-0000-1000-8000-00805F9B0131   监听特征值  0003CDD1-0000-1000-8000-00805F9B0131   写入特征值  0003CDD2-0000-1000-8000-00805F9B0131
        if (item.uuid === '0003CDD0-0000-1000-8000-00805F9B0131') {
          getBLEDeviceCharacteristics(deviceId, item.uuid)
        }
      })
    },
    fail: (err) => {
      console.log(err)
    },
  })
}

//获取蓝牙设备某个服务中的所有特征值
const getBLEDeviceCharacteristics = (deviceId: string, serviceId: string) => {
  console.log('获取蓝牙设备某个服务中的所有特征值')
  uni.getBLEDeviceCharacteristics({
    deviceId,
    serviceId,
    success: (res) => {
      console.log(res, '获取特征成功')
      res.characteristics.forEach((item) => {
        //必须设备的特征值支持 notify 或者 indicate 才可以成功调用
        if (item.properties.notify && item.uuid == '0003CDD1-0000-1000-8000-00805F9B0131') {
          console.log('可以设备接受数据')
          notifyBLECharacteristicValueChange(deviceId, serviceId, item.uuid)
        }
        if (item.uuid == '0003CDD2-0000-1000-8000-00805F9B0131' && item.properties.write) {
          console.log('可以设备写入数据')
          sendPassword(deviceId, serviceId, item.uuid)
          queryDeviceStatus(deviceId, serviceId, item.uuid)
        }
      })
    },
    fail: (err) => {
      console.log(err)
    },
  })
}
//处理十进制字符串
const formatConversion = (array: number[]) => {
  const hexString = Array.from(array)
    .map((byte) => byte.toString(16).padStart(2, '0').toLowerCase())
    .join('')
  console.log(hexString)
  console.log(hexString[22] + hexString[23] + 'hello')
  if (hexString[24] == 0 && hexString[25] == 0) {
    connectBLEsucess.value = true
    console.log('无硬件问题')
    uni.navigateTo({
      url: `/pagesDevice/calibrate-equipment/calibrate-equipment?deviceId=${deviceId.value}`,
    })
  } else {
    uni.showToast({
      title: '设备硬件出错，请联系客服',
      icon: 'none',
      duration: 2000,
    })
  }
}

//接受设备数据 走监听通道
const notifyBLECharacteristicValueChange = (
  deviceId: string,
  serviceId: string,
  characteristicId: string,
) => {
  uni.notifyBLECharacteristicValueChange({
    deviceId,
    serviceId,
    characteristicId,
    state: true,
    success: (res) => {
      console.log(res)
      //监听设备发送数据
      uni.onBLECharacteristicValueChange((res) => {
        console.log(res.value)
        formatConversion(new Uint8Array(res.value))
      })
    },
    fail: (err) => {
      console.log(err)
    },
  })
}

//发送密码
const sendPassword = (deviceId: string, serviceId: string, characteristicId: string) => {
  console.log('发送密码')
  dataTransforma('PWTAOS', direct.value)
  BleWrite(deviceId, serviceId, characteristicId, direct.value)
}
//查询设备状态
const queryDeviceStatus = (deviceId: string, serviceId: string, characteristicId: string) => {
  console.log('查询设备状态')
  dataTransforma('TAOSH', direct.value)
  console.log(deviceId)
  BleWrite(deviceId, serviceId, characteristicId, direct.value)
}

//定时关闭蓝牙
const timeoutId = setTimeout(() => {
  if (isCreateBLEConnection.value) {
    return
  }
  uni.closeBluetoothAdapter({
    success: (res) => {
      clearTimeout(timeoutId)
      console.log(res)
    },
    fail: (err) => {
      console.log(err)
    },
  })
}, 120000)

//处理点击设备
const handleClick = (deviceNum: string) => {
  if (props.type === 'bind') {
    closepopup()
    binddevice(deviceNum)
  } else if (props.type === 'calibrate') {
    createBLEConnection(deviceId.value)
  }
}

//绑定设备
const binddevice = async (deviceNum: string) => {
  const mes = await bindDeviceApi({
    bindFlg: 1,
    deviceNum,
    userId: memberStore.profile!.id,
  })
  console.log(mes)
  if (mes.msg === '对象正常') {
    uni.showToast({
      title: '绑定成功',
      icon: 'none',
      duration: 3000,
    })
    uni.navigateBack({
      delta: 1,
    })
    //修改store中的设备列表
    await deviceStore.getDeviceList()
    //请求设备实时数据
    await deviceStore.getDeviceData()
  } else {
    uni.showToast({
      title: '绑定失败',
      icon: 'none',
      duration: 1000,
    })
  }
}
const back = () => {
  uni.navigateBack({
    delta: 1,
  })
}

onUnload(() => {
  if (connectBLEsucess.value === true) return
  uni.closeBluetoothAdapter({
    success: (res) => {
      clearTimeout(timeoutId)
      console.log(res + '关闭蓝牙')
    },
    fail: (err) => {},
  })
})
</script>
<template>
  <view class="content">
    <view class="back">
      <u-icon name="arrow-left" color="#000000" size="22" @click="back"></u-icon>
    </view>
    <view class="title">已搜寻到以下设备</view>
    <view class="remind">(下滑画面重新搜索)</view>
    <scroll-view scroll-y class="scroll-view">
      <view
        class="device-item"
        v-for="(item, index) in btdevicelist"
        :key="index"
        @click="handleClick(item.name)"
        >{{ item.name }}
      </view>
    </scroll-view>
    <!-- <u-popup :show="show" mode="center" @close="closepopup" class="frist">
      <up-loadmore status="loading" loading-text="搜索中" />
    </u-popup> -->
  </view>
</template>
<style lang="scss">
page {
  height: 100%;
  font-family: PingFangSC-regular;
  overflow: hidden;
  .content {
    height: 100%;
    display: flex;
    flex-direction: column;
    .back {
      position: relative;
      margin-top: 115.385rpx;
      margin-bottom: 28.846rpx;
      height: 42.308rpx;
      font-size: 34.615rpx;
      text-align: center;
      .u-icon {
        position: absolute;
        left: 3%;
      }
    }
    .title {
      //padding-top: 173.077rpx;
      padding-bottom: 19.231rpx;
      margin-left: 28.846rpx;
      font-size: 46.154rpx;
    }
    .remind {
      font-size: 28.846rpx;
      margin-left: 28.846rpx;
      color: #999999;
      margin-bottom: 28.846rpx;
    }
    .scroll-view {
      overflow: hidden;
      .device-item {
        width: 90%;
        height: 86.538rpx;
        line-height: 86.538rpx;
        margin: 0 auto 9.615rpx;
        padding-left: 19.231rpx;
        background-color: #f4f3f8;
      }
    }
    .u-popup__content {
      background-color: #444444;
      color: #fefefe;
      .u-safe-area-inset-bottom {
        padding-bottom: 0;
      }
    }
    .u-loadmore__content {
      display: flex;
      flex-direction: column;
      width: 192.308rpx;
      height: 173.077rpx;
      .u-loadmore__content__icon-wrap {
        margin: 0 auto 19.231rpx;
      }
    }
  }
}
</style>
